﻿using System;
using Airborne.ScrumPoker.Module.Developer.Views;
using Airborne.ScrumPoker.Module.Events;
using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Wpf.Events;
using Microsoft.Practices.Unity;

namespace Airborne.ScrumPoker.Module.Developer.Controllers
{
    public class LogOnController : ILogOnController, IDisposable
    {
        #region Constructor
        public LogOnController(IEventAggregator eventAggregator, IUnityContainer container)
        {
            EventAggregator = eventAggregator;
            Container = container;
        }
        #endregion

        #region Properties

        private IEventAggregator EventAggregator { get; set; }
        private IUnityContainer Container { get; set; }
        private ILogOnView LoginView { get; set; }
        #endregion


        public void Run()
        {
            LoginView = Container.Resolve<ILogOnView>();
            SubscribeToEvents();

            LoginView.SetUserName(Environment.UserName);
             
            LoginView.ShowView();
        }

        private void SubscribeToEvents()
        {
            LoginView.LogOnCanceled += LoginCancelled;
            LoginView.Subscribe += Subscribe;
            EventAggregator.GetEvent<GenericEvent<string>>().Subscribe(ClientSubscribed, ThreadOption.UIThread, true, p => p.Topic == EventTopics.ClientSubscribed);
        }

        private void Subscribe(object sender, GenericEventArgs<string> e)
        {
            EventAggregator.GetEvent<GenericEvent<string>>().Publish(new EventParameters<string>(EventTopics.SubscribeClient, e.Data));
        }

        private void LoginCancelled(object sender, EventArgs e)
        {
            EventAggregator.GetEvent<GenericEvent<int>>().Publish(new EventParameters<int>(EventTopics.Kill, 0));
        }

        private void ClientSubscribed(EventParameters<string> parameters)
        {
            LoginView.CloseView();
        }

        #region IDisposable Members

        public void Dispose()
        {
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (LoginView != null)
                {
                    LoginView.LogOnCanceled -= LoginCancelled;
                    LoginView.Subscribe -= Subscribe;
                }
            }
        }
        #endregion

    }
}
